﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008, 2009 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using EngineOfEvermore.Common;

namespace EngineOfEvermore.Editor.SceneEditor.PropertyEditor
{
    abstract class AbstractActionAdapter : IEventAdapter 
    {
        Action _action;
        Delegate _delegate;
        Object _eventOwner;
        EventDescriptor _eventDescriptor;

        public AbstractActionAdapter( Object eventOwner, EventDescriptor eventDescriptor )
        {
            _eventOwner = eventOwner;
            _eventDescriptor = eventDescriptor;
        }

        public void Subscribe( Action action )
        {
            _action = action;
            _delegate = Delegate.CreateDelegate( _eventDescriptor.EventType, this, "_eventHandler" );
            _eventDescriptor.AddEventHandler( _eventOwner, _delegate );
        }

        public void Unsubscribe()
        {
            _eventDescriptor.RemoveEventHandler( _eventOwner, _delegate );
        }

        protected void _executeAction()
        {
            _action();
        }
    }

    class ActionAdapter : AbstractActionAdapter
    {
        public ActionAdapter( Object eventOwner, EventDescriptor eventDescriptor ) :
            base( eventOwner, eventDescriptor )
        {}

        private void _eventHandler() { _executeAction(); }
    }

    class ActionAdapter<T> : AbstractActionAdapter
    {
        public ActionAdapter( Object eventOwner, EventDescriptor eventDescriptor ):
            base ( eventOwner, eventDescriptor )
        {   
        }

        private void _eventHandler( T arg1 ) { _executeAction(); }
    }

    class ActionAdapter<T1, T2> : AbstractActionAdapter
    {
        public ActionAdapter( Object eventOwner, EventDescriptor eventDescriptor ) :
            base( eventOwner, eventDescriptor )
        {
        }

        private void _eventHandler( T1 arg1, T2 arg2 ) { _executeAction(); }
    }

    class ActionAdapter<T1, T2, T3> : AbstractActionAdapter
    {
        public ActionAdapter( Object eventOwner, EventDescriptor eventDescriptor ) :
            base( eventOwner, eventDescriptor )
        {
        }

        private void _eventHandler( T1 arg1, T2 arg2, T3 arg3 ) { _executeAction(); }
    }

    class ActionAdapter<T1, T2, T3, T4> : AbstractActionAdapter
    {
        public ActionAdapter( Object eventOwner, EventDescriptor eventDescriptor ) :
            base( eventOwner, eventDescriptor )
        {
        }

        private void _eventHandler( T1 arg1, T2 arg2, T3 arg3, T4 arg4 ) { _executeAction(); }
    }
    
    class ActionAdapterFactory
    {
        private static readonly Type[] _constructorSignature = 
            new Type[] { typeof( Object ), typeof( EventDescriptor ) };
        
        private static readonly AdapterConstructorCache _constructorCache = 
            new AdapterConstructorCache();

        class AdapterConstructorCache
        {
            class Entry
            {
                public Entry( Type[] typeArgs, ConstructorInfo constructorInfo )
                {
                    this.TypeArgs = typeArgs;
                    this.ConstructorInfo = constructorInfo;
                }

                public readonly Type[] TypeArgs;
                public readonly ConstructorInfo ConstructorInfo;
            }

            private static readonly Type[] _adapterTemplates = new Type[] 
            { 
                typeof ( ActionAdapter ),
                typeof ( ActionAdapter<> ),
                typeof ( ActionAdapter<,> ),
                typeof ( ActionAdapter<,,>),
                typeof ( ActionAdapter<,,,>)
            };

            private static readonly ConstructorInfo _actionAdapterConstructor = 
                typeof( ActionAdapter ).GetConstructor( _constructorSignature );

            List<Entry> _entries = new List<Entry>();

            public ConstructorInfo this[Type[] typeArgs]
            {
                get
                {
                    var entry = _entries.Find( e => e.TypeArgs.SequenceEqual( typeArgs ) );

                    if ( entry == null )
                    {
                        if ( typeArgs.Length == 0 )
                        {
                            entry = new Entry( typeArgs, _actionAdapterConstructor );
                            _entries.Add( entry );
                        }
                        else
                        {
                            Type adapterTemplate = _adapterTemplates[typeArgs.Length];

                            var concreteAdapterType = adapterTemplate.MakeGenericType( typeArgs );
                            var ctor = concreteAdapterType.GetConstructor( _constructorSignature );

                            entry = new Entry( typeArgs, ctor );
                            _entries.Add( entry );
                        }
                    }

                    return entry.ConstructorInfo;
                }
            }
        }

        public static IEventAdapter Create( Object eventOwner, EventDescriptor eventDescriptor )
        {
            Debug.Assert( _isAction( eventDescriptor.EventType ) );

            var constructor = _getConstructor( eventDescriptor );
            return (IEventAdapter)constructor
                .Invoke( new Object[] { eventOwner, eventDescriptor } );
        }

        private static bool _isAction( Type type )
        {
            if ( type.TypeHandle.Equals( typeof( Action ).TypeHandle ) )
                return true;

            if ( type.IsGenericType && !type.ContainsGenericParameters )
            {
                Type template = type.GetGenericTypeDefinition();

                if ( template.TypeHandle.Equals( typeof( Action<> ).TypeHandle ) ||
                    template.TypeHandle.Equals( typeof( Action<,> ).TypeHandle ) ||
                    template.TypeHandle.Equals( typeof( Action<,,> ).TypeHandle ) ||
                    template.TypeHandle.Equals( typeof( Action<,,,> ).TypeHandle )
                    )
                    return true;
            }

            return false;
        }

        public static IEventAdapter Create( Object eventOwner, String eventName )
        {
            var eventDescriptor = TypeDescriptor.GetEvents( eventOwner ).Find( eventName, false );

            return Create( eventOwner, eventDescriptor );
        }

        private static ConstructorInfo _getConstructor( EventDescriptor eventDescriptor )
        {
            Type[] typeArguments = eventDescriptor.EventType.GetGenericArguments();

            return _constructorCache[typeArguments];
        }
    }

    #if ENGINE_OF_EVERMORE_ENABLE_UNIT_TESTS
    namespace Test
    {
        [TestFixture]
        public class ActionAdapterTestFixture
        {
            class ClassWithEvents
            {
                public event Action SimpleEvent;
                public event Action<int> IntEvent;
                public event Action<String> StringEvent;

                public event Action<Object, String> ObjectStringEvent;
                public event Action<Object, Vector2d> ObjectVector2dEvent;

                public event EventHandler StandardEvent;

                internal void RaiseIntEvent()
                {
                    if ( this.IntEvent != null )
                        this.IntEvent( 42 );
                }

                internal void RaiseStringEvent()
                {
                    if ( this.StringEvent != null )
                        this.StringEvent( String.Empty );
                }

                internal void RaiseSimpleEvent()
                {
                    if ( this.SimpleEvent != null )
                        this.SimpleEvent();
                }

                internal void RaiseObjectStringEvent()
                {
                    if ( this.ObjectStringEvent != null )
                        this.ObjectStringEvent( null, null );
                }

                internal void RaiseObjectVector2dEvent()
                {
                    if ( this.ObjectVector2dEvent != null )
                        this.ObjectVector2dEvent( null, Vector2d.Zero );
                }

                internal void RaiseStandardEvent()
                {
                    if ( this.StandardEvent != null )
                        this.StandardEvent( null, null );
                }
            }

            [Test]
            public void TestCreation()
            {
                var publisher = new ClassWithEvents();

                IEventAdapter adapter = ActionAdapterFactory.Create( publisher, "IntEvent" );

                Assert.That( adapter, Is.Not.Null );
            }

            [Test]
            public void TestSubscriptionWithInt()
            {
                var publisher = new ClassWithEvents();
                bool handlerExecuted = false;
                Action eventHandler = () => { handlerExecuted = true; };

                IEventAdapter adapter = ActionAdapterFactory.Create( publisher, "IntEvent" );

                adapter.Subscribe( eventHandler );
                publisher.RaiseIntEvent();

                Assert.That( handlerExecuted, Is.True );
            }

            [Test]
            public void TestSubscriptionWithOtherTypeThanInt()
            {
                var publisher = new ClassWithEvents();
                bool handlerExecuted = false;
                Action eventHandler = () => { handlerExecuted = true; };

                IEventAdapter adapter = ActionAdapterFactory.Create( publisher, "StringEvent" );

                adapter.Subscribe( eventHandler );
                publisher.RaiseStringEvent();

                Assert.That( handlerExecuted, Is.True );
            }

            [Test]
            public void TestSubscriptionWithSimpleEvent()
            {
                var publisher = new ClassWithEvents();
                bool handlerExecuted = false;
                Action eventHandler = () => { handlerExecuted = true; };

                IEventAdapter adapter = ActionAdapterFactory.Create( publisher, "SimpleEvent" );

                adapter.Subscribe( eventHandler );
                publisher.RaiseSimpleEvent();

                Assert.That( handlerExecuted, Is.True );
            }

            [Test]
            public void TestSubscriptionWith2EventArgs()
            {
                var publisher = new ClassWithEvents();
                bool handlerExecuted = false;
                Action eventHandler = () => { handlerExecuted = true; };

                IEventAdapter adapter = ActionAdapterFactory.Create( publisher, 
                    "ObjectStringEvent" );

                adapter.Subscribe( eventHandler );
                publisher.RaiseObjectStringEvent();

                Assert.That( handlerExecuted, Is.True );
            }

            [Test]
            public void TestSubscriptionWith2EventArgs2()
            {
                var publisher = new ClassWithEvents();
                bool handlerExecuted = false;
                Action eventHandler = () => { handlerExecuted = true; };

                IEventAdapter adapter = ActionAdapterFactory.Create( publisher, 
                    "ObjectVector2dEvent" );

                adapter.Subscribe( eventHandler );
                publisher.RaiseObjectVector2dEvent();

                Assert.That( handlerExecuted, Is.True );
            }
        }
    }
    #endif
}
